package controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import models.Device;
import models.SystemParams;
import models.User;
import models.WebHraDetail;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import play.Play;
import play.data.validation.Required;
import play.libs.Codec;
import play.libs.Files;
import services.DeviceService;
import services.HraDetailService;
import services.SystemParamService;
import services.UploadToAppService;
import services.WebHraDetailService;
import utils.IdCardUtil;
import utils.UUIDString;
import utils.Base64Util;
import utils.BizConstants;
import utils.Validate;
import vos.AppDataVo;
import vos.DeviceVo;
import vos.ReturnCode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aton.db.SessionFactory;

public class HeathDataController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(HeathDataController.class);
	private static final SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat Formater = new SimpleDateFormat("yyyyMMdd");
		/**
		 * HRA数据上传接口
		 *
		 * @Title: heathData 
		 * @param userinfo 用户信息
		 * @param detail 体检数据
		 * @param pdf 体检报告
		 * @return: void
		 */
		public static void heathData(String deviceid,String userinfo,String detail, File pdf,
				File pic_erbihou,File pic_guge,File pic_huxi,
				File pic_miniaoshengzhi,File pic_shenjing,
				File pic_xiaohua,File pic_xinxueguan){
			if(StringUtils.isEmpty(userinfo)||StringUtils.isEmpty(deviceid)||
					StringUtils.isEmpty(detail)){
				log.warn("上传数据为空值");
				renderFailedJson(ReturnCode.ErrorCode, "上传数据为空值");
			}
			DeviceVo device=DeviceService.getViewById(deviceid);
			if(device==null){
				renderFailedJson(ReturnCode.REUPLOAD, "设备不存在");
			}
			if(device.isflag){
				renderFailedJson(ReturnCode.REUPLOAD, "设备已被停用");
			}
			//将字符串转换为实体类
			User newuser=new User();
			WebHraDetail webHra=new WebHraDetail();
			try{
				newuser=JSONObject.parseObject(userinfo, User.class);
				webHra=JSONObject.parseObject(detail, WebHraDetail.class);
				webHra.deviceid=deviceid;
			}catch(Exception e){
				e.printStackTrace();
				log.warn("字符串解析失败");
				renderFailedJson(ReturnCode.ErrorCode, "字符串解析失败");
			}
			//判断用户身份证号是不是空，身份证格式是否正确
			if(StringUtils.isEmpty(newuser.idcard)||!IdCardUtil.verify(newuser.idcard)){
				log.warn("身份证格式不正确");
				renderFailedJson(ReturnCode.ErrorCode, "身份证格式不正确");
			}
			newuser.idcard=newuser.idcard.toUpperCase();
			//验证用户是不是存在，不存在需要新注册
			String user=User.findIdcardById(newuser.idcard);
			if(StringUtils.isEmpty(user)){
				log.warn(newuser.username+"的身份证号不存在需注册");
				boolean isDoRegist=doRegist(newuser);
				if(!isDoRegist){
					log.warn("新用户注册失败");
					renderFailedJson(ReturnCode.ErrorCode, "新用户注册失败");
				}
			}
			else{
				boolean isUpdate=doUpdate(newuser);
				if(!isUpdate){
					log.warn("用户信息更新失败");
					renderFailedJson(ReturnCode.ErrorCode, "用户信息更新失败");
				}
			}
			//保存附件，目录为/public/upload
			if(pdf==null){
				log.warn("体检报告为空");
				renderFailedJson(ReturnCode.ErrorCode, "体检报告不能为空");
			}
			if(StringUtils.isEmpty(webHra.huiyuanziliao_jianchariqi)){
				log.warn("检查日期为空");
				renderFailedJson(ReturnCode.ErrorCode, "检查日期不能为空");
			}
			//格式化检查日期
			Date examDate=getExamDate(webHra.huiyuanziliao_jianchariqi);
			if(examDate==null){
				log.warn("检查日期格式化失败");
				renderFailedJson(ReturnCode.ErrorCode, "检查日期格式化失败");
			}
			webHra.huiyuanziliao_jianchariqi=dateFormater.format(examDate);
			webHra.iscount=isCount(webHra.huiyuanziliao_jianchariqi,newuser.idcard,device.space);
			boolean issave=saveFile(newuser,webHra,examDate,deviceid,pic_erbihou,pic_guge,pic_huxi,
					pic_miniaoshengzhi,pic_shenjing,
					pic_xiaohua,pic_xinxueguan,pdf);
			if(!issave){
				renderFailedJson(ReturnCode.ErrorCode, "保存文件失败");
			}
			/**
			 * 机构不为空时，上传pdf和用户信息到app
			 */
			if(StringUtils.isNotEmpty(device.organization)){
				boolean isupload=UploadToAppService.uploadToApp(pdf,device.organization,newuser.idcard,webHra.pdfname,webHra.huiyuanziliao_jianchariqi+" "+webHra.huiyuanziliao_jianchashijian+":00");
				if(!isupload){
					log.warn("数据上传失败");
					webHra.isupload=false;
				}else{
					webHra.isupload=true;
				}
			}
			else{
				webHra.isupload=false;
			}
			boolean isReport=doSaveReport(webHra,newuser.idcard);
			if(!isReport){
				log.warn("用户体检报告保存失败");
				renderFailedJson(ReturnCode.ErrorCode, "用户体检报告保存失败");
			}
			renderFailedJson(ReturnCode.SuccessCode, "保存成功");
		}
		
		/**
		 * 保存文件
		 * @param webHra 
		 * @param newuser 
		 * @param examDate 
		 * @param deviceid 
		 *
		 * @Title: saveFile 
		 * @param wenjian_pic_erbihou
		 * @param wenjian_pic_guge
		 * @param wenjian_pic_huxi
		 * @param wenjian_pic_miniaoshengzhi
		 * @param wenjian_pic_shenjing
		 * @param wenjian_pic_xiaohua
		 * @param wenjian_pic_xinxueguan
		 * @param pdf 
		 * @return: void
		 */
		private static boolean saveFile(User newuser, WebHraDetail webHra, Date examDate, String deviceid, 
				File wenjian_pic_erbihou, File wenjian_pic_guge, File wenjian_pic_huxi,
				File wenjian_pic_miniaoshengzhi, File wenjian_pic_shenjing, File wenjian_pic_xiaohua,
				File wenjian_pic_xinxueguan, File pdf) {
			// TODO Auto-generated method stub
			//获取文件名称
			String date=Formater.format(examDate);
			String number=getPdfName(newuser.idcard,examDate);
			String pdfname=newuser.idcard+"_"+date+number;
			String wenjian_pic_erbihou_path=newuser.idcard+"_wenjian_pic_erbihou"+number;
			String wenjian_pic_guge_path=newuser.idcard+"_wenjian_pic_guge"+number;
			String wenjian_pic_huxi_path=newuser.idcard+"_wenjian_pic_huxi"+number;
			String wenjian_pic_miniaoshengzhi_path=newuser.idcard+"_wenjian_pic_miniaoshengzhi"+number;
			String wenjian_pic_xiaohua_path=newuser.idcard+"_wenjian_pic_xiaohua"+number;
			String wenjian_pic_shenjing_path=newuser.idcard+"_wenjian_pic_shenjing"+number;
			String wenjian_pic_xinxueguan_path=newuser.idcard+"_wenjian_pic_xinxueguan"+number;
			if(StringUtils.isEmpty(pdfname)){
				log.warn("获取pdf名称失败");
				return false;
			}
			String nowDate=Formater.format(examDate);
			String filePath = BizConstants.filePath+deviceid+"/"+nowDate+"/"+newuser.idcard+"/";
			Files.copy(pdf, Play.getFile(filePath+pdfname+".pdf"));
			if(wenjian_pic_erbihou!=null){
				Files.copy(wenjian_pic_erbihou, Play.getFile(filePath+wenjian_pic_erbihou_path+".jpg"));
				webHra.erbihoupic=wenjian_pic_erbihou_path+".jpg";
			}
			if(wenjian_pic_guge!=null){
				Files.copy(wenjian_pic_guge, Play.getFile(filePath+wenjian_pic_guge_path+".jpg"));
				webHra.gugepic=wenjian_pic_guge_path+".jpg";
			}
			if(wenjian_pic_huxi!=null){
				Files.copy(wenjian_pic_huxi, Play.getFile(filePath+wenjian_pic_huxi_path+".jpg"));		
				webHra.huxipic=wenjian_pic_huxi_path+".jpg";
			}
			if(wenjian_pic_miniaoshengzhi!=null){
				Files.copy(wenjian_pic_miniaoshengzhi, Play.getFile(filePath+wenjian_pic_miniaoshengzhi_path+".jpg"));
				webHra.miniaoshengzhipic=wenjian_pic_huxi_path+".jpg";
			}
			if(wenjian_pic_xiaohua!=null){
				Files.copy(wenjian_pic_xiaohua, Play.getFile(filePath+wenjian_pic_xiaohua_path+".jpg"));
				webHra.xiaohuapic=wenjian_pic_huxi_path+".jpg";
			}
			if(wenjian_pic_shenjing!=null){
				Files.copy(wenjian_pic_shenjing, Play.getFile(filePath+wenjian_pic_shenjing_path+".jpg"));
				webHra.shenjingpic=wenjian_pic_huxi_path+".jpg";
			}
			if(wenjian_pic_xinxueguan!=null){
				Files.copy(wenjian_pic_xinxueguan, Play.getFile(filePath+wenjian_pic_xinxueguan_path+".jpg"));
				webHra.xinxueguanpic=wenjian_pic_huxi_path+".jpg";
			}
			webHra.pdfname=pdfname+".pdf";
			return true;
		}
		/**
		 * 格式化检查日期为日期格式
		 *
		 * @Title: getExamDate 
		 * @param huiyuanziliao_jianchariqi
		 * @return
		 * @return: Date
		 */
		private static Date getExamDate(String jianchariqi) {
			// TODO Auto-generated method stub
//			String[] riqi=jianchariqi.split("\\.");
//			if(riqi.length==0){
//				return null;
//			}
//			String dateString=riqi[2]+"-"+riqi[1]+"-"+riqi[0];
			try {
				Date date=dateFormater.parse(jianchariqi);
				return date;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				return null;
			}
		}
		/**
		 * 获取文件序号
		 *
		 * @Title: getPdfName 
		 * @param idcard 用户身份证
		 * @param examDate 
		 * @return
		 * @return: String
		 */
		private static String getPdfName(String idcard, Date examDate) {
			// TODO Auto-generated method stub
			String dateString=dateFormater.format(examDate);
			//从数据库获取该用户今日体检数目+1作为序号
			long sort=WebHraDetailService.getUserPdf(idcard,dateString);
			String pdfname=(sort+1)<10?"_0"+(sort+1):"_"+(sort+1);
			return pdfname;
		}
		/**
		 * 保存用户体检数据
		 *
		 * @Title: doSaveReport 
		 * @param webHra HRA 体检数据
		 * @return
		 * @return: boolean
		 */
		private static boolean doSaveReport( WebHraDetail webHra,String userid) {
			// TODO Auto-generated method stub
			//设置pdf名称
//			if(StringUtils.isNotEmpty(filename)){
//				webHra.pdfname=filename;
//			}
			//设置身份证号
			webHra.idcard=userid;
			try{
				WebHraDetailService.insertHRAData(webHra);
			}
			catch(Exception e){
				return false;
			}
			return true;
		}
		/**
		 * 更新用户
		 *
		 * @Title: doupdate 
		 * @param newuser 新用户
		 * @param user 现有用户
		 * @return: void
		 */
		private static boolean doUpdate(User newuser) {
			// TODO Auto-generated method stub
			if(StringUtils.isEmpty(newuser.idcard)){
				return false;
			}
			try{
				newuser.update();
			}
			catch(Exception e){
				return false;
			}
			return true;
		}
		/**
		 * 注册用户
		 *
		 * @Title: doregist 
		 * @param newuser 新用户
		 * @return: void
		 */
		
		private static boolean doRegist(User newuser) {
			// TODO Auto-generated method stub
			if(StringUtils.isEmpty(newuser.idcard)){
				return false;
			}
			//创建方式为：设备上传
			newuser.createway=BizConstants.USER_CREATEWAY_UPLOAD;
			try{
				newuser.create();
			}
			catch(Exception e){
				return false;
			}
			return true;
		}
		/**
		 * 检测数据是否需要统计
		 * @param space2 
		 *
		 * @Title: iscount 
		 * @return
		 * @return: boolean
		 */
		public static boolean isCount(String huiyuanziliao_jianchariqi,String idcard,String space){
//			String param=SystemParamService.getByCacheId(BizConstants.PERSON_VALIDITY_TERM);
//			if(StringUtils.isEmpty(param)){
//				return true;
//			}
			/**
			 * 当前日期减去系统参数中的时间，查询该人员在这段时间是否存在统计记录，不存在返回true
			 */
			if(StringUtils.isEmpty(space)){
				return true;
			}
			DateTime date=DateTime.parse(huiyuanziliao_jianchariqi).minusDays(Integer.parseInt(space));
			String datetime=date.toString("yyyy-MM-dd");
			String hra=HraDetailService.getTimeCount(idcard,datetime,huiyuanziliao_jianchariqi);
			if(StringUtils.isEmpty(hra)){
				return true;
			}
			return false;
		}
}
